
using System;
using System.Data;
using System.Linq;
using System.Linq.Dynamic;
using System.Linq.Dynamic.Core;
using System.Linq.Expressions;
using System.Threading.Tasks;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;

using Abp.UI;
using Abp.AutoMapper;
using Abp.Extensions;
using Abp.Authorization;
using Abp.Domain.Repositories;
using Abp.Application.Services.Dto;
using Abp.Linq.Extensions;
 
using JYJ.AiYard.StationManagement.TbYIDEINVParams.Dtos;
using JYJ.AiYard.StationManagement.TbYIDEINVParams.DomainService;
using JYJ.AiYard.StationManagement.TbYIDEINVParams.Authorization;
using Microsoft.AspNetCore.Http;
using JYJ.AiYard.Database;
using JYJ.AiYard.StationManagement.YardReport;
using JYJ.AiYard.StationManagement.YardCommonHald;

namespace JYJ.AiYard.StationManagement.TbYIDEINVParams
{
    /// <summary>
    /// TbYIDEINVParams应用层服务的接口实现方法  
    ///</summary>
    [AbpAuthorize]
    public class TbYIDEINVParamsAppService : AiYardAppServiceBase, ITbYIDEINVParamsAppService
    {
        private readonly IRepository<TbYIDEINVParams, long> _entityRepository;

        private readonly ITbYIDEINVParamsManager _entityManager;

		protected IHttpContextAccessor _httpContext;

		private readonly IHttpService _httpService;
		/// <summary>
		/// 构造函数 
		///</summary>
		public TbYIDEINVParamsAppService(
        IRepository<TbYIDEINVParams, long> entityRepository
        ,ITbYIDEINVParamsManager entityManager
		,IHttpContextAccessor httpContextAccessor
		,IHttpService httpService
		)
        {
            _entityRepository = entityRepository; 
            _entityManager=entityManager;
			_httpContext = httpContextAccessor;
			_httpService = httpService;
		}


        /// <summary>
        /// 获取TbYIDEINVParams的分页列表信息
        ///</summary>
        /// <param name="input"></param>
        /// <returns></returns>
		[AbpAuthorize(TbYIDEINVParamsPermissions.Query)] 
        public async Task<PagedResultDto<TbYIDEINVParamsListDto>> GetPaged(GetTbYIDEINVParamssInput input)
		{
			List<long> StationList = new List<long>();
			tbQFilterText filterText = input.FilterText.ToObject<tbQFilterText>();
			if (filterText.StationId == null || filterText.StationId <= 0)
			{
				StationList = GetCurrenUserOrganizationAndChildrenUnit();
			}
			else
			{
				StationList.Add((long)filterText.StationId);
			}
			var query = _entityRepository.GetAll().Where(o => StationList.Contains(o.Station_ID));
			// TODO:根据传入的参数添加过滤条件
            

			var count = await query.CountAsync();

			var entityList = await query               
                    .OrderBy(input.Sorting).AsNoTracking()
					.PageBy(input)
					.ToListAsync();

			// var entityListDtos = ObjectMapper.Map<List<TbYIDEINVParamsListDto>>(entityList);
			var entityListDtos =entityList.MapTo<List<TbYIDEINVParamsListDto>>();

			return new PagedResultDto<TbYIDEINVParamsListDto>(count,entityListDtos);
		}


		/// <summary>
		/// 通过指定id获取TbYIDEINVParamsListDto信息
		/// </summary>
		[AbpAuthorize(TbYIDEINVParamsPermissions.Query)] 
		public async Task<TbYIDEINVParamsListDto> GetById(EntityDto<long> input)
		{
			var entity = await _entityRepository.GetAsync(input.Id);

		    return entity.MapTo<TbYIDEINVParamsListDto>();
		}

		/// <summary>
		/// 获取编辑 TbYIDEINVParams
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		[AbpAuthorize(TbYIDEINVParamsPermissions.Create,TbYIDEINVParamsPermissions.Edit)]
		public async Task<GetTbYIDEINVParamsForEditOutput> GetForEdit(NullableIdDto<long> input)
		{
			var output = new GetTbYIDEINVParamsForEditOutput();
            TbYIDEINVParamsEditDto editDto;

			if (input.Id.HasValue)
			{
				var entity = await _entityRepository.GetAsync(input.Id.Value);

				editDto = entity.MapTo<TbYIDEINVParamsEditDto>();
			}
			else
			{
				editDto = new TbYIDEINVParamsEditDto();
			}

			output.TbYIDEINVParams = editDto;
			return output;
		}


		/// <summary>
		/// 添加或者修改TbYIDEINVParams的公共方法
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		[AbpAuthorize(TbYIDEINVParamsPermissions.Create,TbYIDEINVParamsPermissions.Edit)]
		public async Task CreateOrUpdate(CreateOrUpdateTbYIDEINVParamsInput input)
		{
            if (input.TbYIDEINVParams.Station_ID <= 0)
            {
                throw new UserFriendlyException("请选择确定的场所名称");
            }
            if (input.TbYIDEINVParams.Id.HasValue)
			{
				await Update(input.TbYIDEINVParams);
			}
			else
			{
				await Create(input.TbYIDEINVParams);
			}
		}


		/// <summary>
		/// 新增TbYIDEINVParams
		/// </summary>
		[AbpAuthorize(TbYIDEINVParamsPermissions.Create)]
		protected virtual async Task<TbYIDEINVParamsEditDto> Create(TbYIDEINVParamsEditDto input)
		{
            if (string.IsNullOrEmpty(input.Client_ID.ToString()))
                input.Client_ID = 0;

             
            //判断相同的客户端是否只存在一个
            var query = _entityRepository.GetAll()
                .Where(o => o.Client_ID == input.Client_ID && o.Station_ID == input.Station_ID && o.YIDE_mch_type==input.YIDE_mch_type);
            if (query.Count() > 0)
            {
                throw new UserFriendlyException("存在相同活动的客户端支付参数设置");
            }

            // var entity = ObjectMapper.Map <TbYIDEINVParams>(input);
            var entity=input.MapTo<TbYIDEINVParams>();
			

			entity = await _entityRepository.InsertAsync(entity);
			return entity.MapTo<TbYIDEINVParamsEditDto>();
		}

		/// <summary>
		/// 编辑TbYIDEINVParams
		/// </summary>
		[AbpAuthorize(TbYIDEINVParamsPermissions.Edit)]
		protected virtual async Task Update(TbYIDEINVParamsEditDto input)
		{
            if (string.IsNullOrEmpty(input.Client_ID.ToString()))
                input.Client_ID = 0;

             
            //判断相同的客户端是否只存在一个
            var query = _entityRepository.GetAll()
                .Where(o => o.Client_ID == input.Client_ID && o.Station_ID == input.Station_ID && o.YIDE_mch_type == input.YIDE_mch_type && o.Id!=input.Id);
            if (query.Count() > 0)
            {
                throw new UserFriendlyException("存在相同活动的客户端支付参数设置");
            }

            var entity = await _entityRepository.GetAsync(input.Id.Value);
			input.MapTo(entity);

			// ObjectMapper.Map(input, entity);
		    await _entityRepository.UpdateAsync(entity);
		}



		/// <summary>
		/// 删除TbYIDEINVParams信息的方法
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		[AbpAuthorize(TbYIDEINVParamsPermissions.Delete)]
		public async Task Delete(EntityDto<long> input)
		{
			//TODO:删除前的逻辑判断，是否允许删除
			await _entityRepository.DeleteAsync(input.Id);
		}



		/// <summary>
		/// 批量删除TbYIDEINVParams的方法
		/// </summary>
		[AbpAuthorize(TbYIDEINVParamsPermissions.BatchDelete)]
		public async Task BatchDelete(List<long> input)
		{
			// TODO:批量删除前的逻辑判断，是否允许删除
			await _entityRepository.DeleteAsync(s => input.Contains(s.Id));
		}

		#region GetInvoiceUrl获取开票二维码
		public string GetInvoiceUrl(long Station_Id)
		{
			string host = _httpContext.HttpContext.Request.Host.Host.Replace("www", "pay").Replace("aiweb", "pay").Replace("webx", "pay").Replace("web.", "minipay.").Replace("yun4.", "pay.").Replace("p.", "t.");
#if DEBUG
			host = "pay.aiyard.cn";
#endif
			long TenantId = AbpSession.TenantId == null ? 0 : (long)AbpSession.TenantId;
			string Url = (host.Contains("minipay.") ? "https://" : "http://") + host + ":1888/api/v1.0/YardLogin/GetNormalUrl?host=https%3A%2F%2F" + host + "%2F&pageName=Invoicerecord&StationId=" + Station_Id.ToString().Trim() + "&SaleId=&BillNo=";
			return _httpService.Get(Url).Replace('"', ' ').Trim();
		}
		#endregion

		#region GetInvoiceUrl获取开票小程序码
		public string GetInvoiceUrl_Mini(long Station_Id, int width, string env_version, string color, bool is_hyaline)
		{
			bool check_path = false;
			if (env_version == "release") { check_path = true; }
			bool auto_color = false;
			string miniParams = "&check_path=" + check_path.ToString() + "&env_version=" + env_version + "&width=" + width + "&auto_color=" + auto_color.ToString() + "&color=" + color + "&is_hyaline=" + is_hyaline.ToString();
			string host = _httpContext.HttpContext.Request.Host.Host.Replace("www", "pay").Replace("aiweb", "pay").Replace("webx", "pay").Replace("web.", "minipay.").Replace("yun4.", "pay.").Replace("p.", "t.");
#if DEBUG
			host = "pay.aiyard.cn";
#endif
			long TenantId = AbpSession.TenantId == null ? 0 : (long)AbpSession.TenantId;
			string Url = (host.Contains("minipay.") ? "https://" : "http://") + host + ":1888/api/v1.0/YardLogin/GetNormalUrl_Mini?host=pages/index/index&pageName=Invoice&StationId=" + Station_Id.ToString().Trim() + "&SaleId=&BillNo=" + miniParams;
			string fileName = _httpService.Get(Url).Replace('"', ' ').Trim();
			if (fileName.StartsWith("!"))
			{
				return fileName;
			}
			return (host.Contains("minipay.") ? "https://" : "http://") + host + ":1888/MiniCode/" + fileName;
		}
		#endregion
		///// <summary>
		///// 导出TbYIDEINVParams为excel表,等待开发。
		///// </summary>
		///// <returns></returns>
		//public async Task<FileDto> GetToExcel()
		//{
		//	var users = await UserManager.Users.ToListAsync();
		//	var userListDtos = ObjectMapper.Map<List<UserListDto>>(users);
		//	await FillRoleNames(userListDtos);
		//	return _userListExcelExporter.ExportToFile(userListDtos);
		//}

	}
}


